package com.djx.controller;

import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.stream.Collectors;

/**
 * @ClassName: JSR303Controller
 * @Description: TODO
 * @author: 星~
 * @date: 2021/10/13 0013 下午 14:59
 */
@RestController
@RequestMapping("/jsr303")
public class JSR303Controller {

    @Data
    class RequestParams {
        @NotEmpty(message = "用户名不能为空")
        @Length(min = 4, max = 9, message = "用户名长度为 4-9位！")
        String username;
        @NotEmpty(message = "密码不能为空")
        @Pattern(regexp = "^[a-zA-Z]{8,16}$", message = "密码为8-16位，且不能为空！")
        String password;
        @NotEmpty(message = "年龄不能为空")
        String age;
    }

    @RequestMapping("/test01")
    public Object cc(@Valid RequestParams params, BindingResult result) {
        if (result.hasErrors()) {
            return result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        }
        return "校验全部通过";
    }

}
